package com.pic4493.entities;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

public class DJson
{
   private DHead _head;
   private JSONObject _body;

   public DHead getHead()
   {
	  return _head;
   }

   public JSONObject getBody()
   {
	  return _body;
   }

   //发送数据使用此方法
   public DJson()
   {
	  _head = new DHead();
	  _body = new JSONObject();
   }

//   public DJson(String str)
//   {
//	  this();
//	  fromJson(str);
//   }

   public static DJson createReceiveDJson(String str)
   {
	  DJson json=new DJson();
	  if(json.fromJson(str))
	  {
		 return json;//成功就返回
	  }
	  else 
	  {
		 return null;//失败则返回空
	  }
   }
   
   public boolean fromJson(String str)
   {
	  try
	  {
		 JSONObject jo = new JSONObject(str);

		 _head = new DHead();
		 _head.fromJson(jo.getJSONObject("head"));

		 _body = jo.optJSONObject("body");
		 return true;
	  }
	  catch (Exception e)
	  {
		 Log.d("ERROR", "DJson_fromJson(str) " + e);
		 return false;
	  }
   }

   public String toJson()
   {
	  JSONObject jo = new JSONObject();
	  try
	  {
		 jo.put("head", getHead().toJson());
		 jo.put("body", getBody());
	  }
	  catch (Exception e)
	  {		 
		 Log.d("ERROR", "DJson_toJson() " + e);
		 e.printStackTrace();
	  }
	  return jo.toString();
   }

   public byte[] toBytes() throws UnsupportedEncodingException
   {
	  return this.toJson().getBytes("utf-8");
   }

}
